﻿using DevComponents.DotNetBar;
using DevComponents.DotNetBar.SuperGrid;
using SDATA;
using SDLL;
using SGUI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace SABI
{
    public partial class frm0244 : Form
    {
        private int TabID = 1;
        string sql = "", _VoucherID, _BatchID;

        public frm0244()
        {
            InitializeComponent();
        }

        private void frm0244_Load(object sender, EventArgs e)
        {
            
        }

        public void AddTab(Form frm, bool closebtnVisible)
        {
            SuperTabItem newtab = TabMain.CreateTab("Tab");
            frm.TopLevel = false;
            frm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            frm.Dock = DockStyle.Fill;
            frm.Show();
            newtab.Name = frm.Name + TabID.ToString();
            newtab.Text = string.Format("[{0}] {1}", TabID, frm.Text);
            newtab.CloseButtonVisible = closebtnVisible;
            newtab.AttachedControl.Controls.Add(frm);
            TabMain.SelectedTabIndex = TabMain.Tabs.Count - 1;
            TabID += 1;
        }

        public void CloseTab()
        {
            if (TabMain.Tabs.Count > 0) { TabMain.Tabs.RemoveAt(TabMain.SelectedTabIndex); }
        }

        void loadDATA_Combo()
        {
            // Kỳ kế toán
            sql = "SELECT DISTINCT";
            sql += " MonthYear , TranMonth , TranYear FROM vi0317 WHERE DivisionID = '" + FRM.DivisionID + "' AND CHARINDEX('" + FRM.ID_Group + "',GroupShow)>0";
            sql += " ORDER BY TranYear DESC, TranMonth DESC";
            DataTable dt_Period = FRM.GetDataTable(sql);
            TDBCboFromPeriod.DataSource = dt_Period;
            TDBCboFromPeriod.SelectedValue = FRM.Period;
            TDBCboToPeriod.DataSource = dt_Period;
            TDBCboToPeriod.SelectedValue = FRM.Period;

            GUI.ChangeDateFormat(DTPFromDate, FRM.SystemDateFormat);
            GUI.ChangeDateFormat(DTPToDate, FRM.SystemDateFormat);
            DTPFromDate.Value = FRM.DateDue;
            DTPToDate.Value = FRM.DateDue;
        }

        public void loadDATA_Grid()
        {
            if (TDBCboFromPeriod.SelectedItem == null || TDBCboToPeriod.SelectedItem == null) { return; }
            sql = "SELECT * FROM vi0202 WHERE DivisionID = '" + FRM.DivisionID + "'";
            if (optFromPeriod.Checked)
            {
                sql += " AND TranMonth+TranYear*100 BETWEEN " + (int.Parse(TDBCboFromPeriod.SelectedItem.ItemData[1]) + int.Parse(TDBCboFromPeriod.SelectedItem.ItemData[2]) * 100).ToString();
                sql += " AND " + (int.Parse(TDBCboToPeriod.SelectedItem.ItemData[1]) + int.Parse(TDBCboToPeriod.SelectedItem.ItemData[2]) * 100).ToString();
            }
            else
            {
                sql += " AND VoucherDate BETWEEN '" + DTPFromDate.Value.ToShortDateString() + "' AND '" + DTPToDate.Value.ToShortDateString() + "'";
            }
            sql += " Order by VoucherTypeID,VoucherDate, VoucherNo";

            DataTable dt_Grid1 = FRM.GetDataTable(sql);
            //DFORMAT.NumberFormat(ref dt_Grid1, new string[] { "OriginalAmount", "ConvertedAmount", "TaxAmount" }, '.');
            DBRender.GridDB(GridDB1, dt_Grid1);
            Application.DoEvents();
        }

        void GetDetail(string VoucherID)
        {
            sql = "SELECT * , tb0054.IsSource,tb0054.IsLimitDate,tb0054.IsLocation, tb0054.IsStocked, tb0054.AccountID as IsDebitAccountID";
            sql += " From tb0191   Left Join tb0054 On tb0191.InventoryID = tb0054.InventoryID";
            sql += " Where VoucherID = '" + VoucherID + "' And TransactionTypeID = 'T03' order by Orders";

            DataTable dt_Grid2 = FRM.GetDataTable(sql);

            DBRender.GridDB(GridDB2, dt_Grid2);
            GridDB2.PrimaryGrid.Footer.Text = String.Format("Tổng số dòng: {0}", dt_Grid2.Rows.Count);
        }

        private void mAdd_Click(object sender, EventArgs e)
        {
            AddTab(new frm0217(), true);
        }

        private void frm0244_Shown(object sender, EventArgs e)
        {
            loadDATA_Combo();
            optFromPeriod.Checked = true;
            RowUpdate();
            GridDB1.Focus();
        }

        private void TDBCboFromPeriod_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (optFromDate.Checked) { loadDATA_Grid(); }
        }

        private void TDBCboToPeriod_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (optFromDate.Checked) { loadDATA_Grid(); }
        }

        private void DTPFromDate_ValueChanged(object sender, EventArgs e)
        {
            if (optFromDate.Checked) { loadDATA_Grid(); }
        }

        private void DTPToDate_ValueChanged(object sender, EventArgs e)
        {
            if (optFromDate.Checked) { loadDATA_Grid(); }
        }

        private void optFromPeriod_CheckedChanged(object sender, EventArgs e)
        {
            loadDATA_Grid();
        }

        private void optFromDate_CheckedChanged(object sender, EventArgs e)
        {
            loadDATA_Grid();
        }

        private void GridDB1_SelectionChanged(object sender, DevComponents.DotNetBar.SuperGrid.GridEventArgs e)
        {
            GridRow gr = (GridRow)e.GridPanel.ActiveRow;
            if (gr == null)
            {
                _VoucherID = "";
                return;
            }
            _VoucherID = gr["clVoucherID"].Value.ToString();
            _BatchID = gr["clBatchID"].Value.ToString();
            GetDetail(_VoucherID);
            RowUpdate();
        }

        public void RowUpdate()
        {
            GridDB1.Update();
            GridDB1.PrimaryGrid.Footer.Text = String.Format("Tổng số dòng: {0:#,#}", GridDB1.PrimaryGrid.Rows.Count);
            if (GridDB1.PrimaryGrid.Rows.Count == 0)
            {
                mEdit.Enabled = false;
                mDelete.Enabled = false;
                mDuplicate.Enabled = false;
                mSystemInfo.Enabled = false;
                mPrint.Enabled = false;
                mSearch.Enabled = false;
                mExportExcel.Enabled = false;
                GridDB2.PrimaryGrid.Rows.Clear();
            }
            else
            {
                mEdit.Enabled = true;
                mDelete.Enabled = true;
                mDuplicate.Enabled = true;
                mSystemInfo.Enabled = true;
                mPrint.Enabled = true;
                mSearch.Enabled = true;
                mExportExcel.Enabled = true;
            }
        }

        private void mEdit_Click(object sender, EventArgs e)
        {
            Form frm = new frm0217(false,false,_VoucherID);
            frm.ShowDialog();
        }

        private void mRefresh_Click(object sender, EventArgs e)
        {
            loadDATA_Grid();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            (Application.OpenForms["frmHOME"] as frmHOME).CloseTab(this);
        }

        private void mSystemInfo_Click(object sender, EventArgs e)
        {
            string tn = "tb0191";
            string ws = string.Format("WHERE VoucherID='{0}'", _VoucherID);
            Form frm = new frm0067(tn, ws);
            frm.ShowDialog();
        }

        private void GridDB1_RowDoubleClick(object sender, GridRowDoubleClickEventArgs e)
        {
            mEdit_Click(null, null);
        }

        private void mDuplicate_Click(object sender, EventArgs e)
        {
            AddTab(new frm0217(false, false, _VoucherID, true), true);
        }

        private void mDelete_Click(object sender, EventArgs e)
        {
            if (GridDB1.PrimaryGrid.GetSelectedRows().Count < 1)
            {
                DLL02.Alert("Bạn phải chọn dòng cần xóa!");
                return;
            }
            if (!DLL02.Confirm("Bạn có chắc muốn xóa?")) { return; }

            sql = string.Format("pr0352 '{0}',{1},{2},'{3}','tb0191','{4}','frm0256'", FRM.DivisionID, FRM.Month, FRM.Year, _VoucherID, _BatchID);
            DataTable dtT = FRM.GetDataTable(sql);
            if (dtT.Rows[0]["Status"].ToString() == "1")
            {
                if (FRM.Lang == "vi") { MessageBox.Show(dtT.Rows[0]["VieMessage"].ToString()); }
                else { MessageBox.Show(dtT.Rows[0]["EngMessage"].ToString()); }
                return;
            }
            sql = string.Format("pr0218 '{0}','{1}','{2}',{3},{4}", _VoucherID, _BatchID, FRM.DivisionID, FRM.Month, FRM.Year);
            DATA.ExecuteNonQuery(sql, FRM.ConnectString);
            sql = string.Format("Delete tb0191 Where VoucherID = '{0}' and TableID ='tb0191' AND DivisionID = '{1}'", _VoucherID, FRM.DivisionID);
            DATA.ExecuteNonQuery(sql, FRM.ConnectString);
            if (GridDB1.PrimaryGrid.SelectedRowCount > 0)
            {
                GridRow gr = (GridRow)GridDB1.PrimaryGrid.GetSelectedRows()[0];
                GridDB1.PrimaryGrid.Rows.RemoveAt(gr.RowIndex);
                RowUpdate();
            }
            DLL02.Info("Xóa dữ liệu thành công!");
        }
        
    }
}
